﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CCWin;
using System.IO.Ports;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Data.SqlClient;

namespace weiqijiance.基类窗体
{
    public partial class UploadAndDownload : CCSkinMain
    {
        public UploadAndDownload()
        {
            InitializeComponent();
        }
        //public mainform m_mainform;
        public string sjcx = "";
        public string sgongwei = "";
        string[] sgongweipeizhi = new string[] {"安综检仪表配置.ini","工位配置.ini","标定数据.ini","串口及通道设置.ini","检测参数设置.ini","检测设备信息设置.ini","检测要求设置.ini","检定系数设置.ini","联网信息设置.ini" };
        private void UploadAndDownload_Load(object sender, EventArgs e)
        {
            cbbjcx.Text = sjcx; 
            cbbgongwei.Text = sgongwei;
            lbljcx.Text = sjcx;
            lblgongwei.Text = sgongwei;
            //获取本地
            getbendipeizhi();
            //获取数据库
            getsqlpeizhi();
            inijcx();
            inigongwei();
        }
        public void inijcx()
        {
            cbbjcx.Items.Add("");
            string ssql = string.Format("select distinct xh from gongweisetting");
            DataTable dt = GetTable(ssql);
            foreach (DataRow dr in dt.Rows)
            {
                cbbjcx.Items.Add(dr["xh"].ToString());
            }
        }
        public void inigongwei()
        {
            cbbgongwei.Items.Add("");
            string ssql = string.Format("select distinct gongwei from gongweisetting");
            DataTable dt = GetTable(ssql);
            foreach (DataRow dr in dt.Rows)
            {
                cbbgongwei.Items.Add(dr["gongwei"].ToString());
            }
        }
        public void getbendipeizhi()
        {
            cbbpzwj.Items.Clear();
            cbbpzwj.Items.Add("");
            listView1.Items.Clear();
            string smubiaolujin = string.Format("{0}", System.Windows.Forms.Application.StartupPath);
            foreach (string sgongweis in sgongweipeizhi)
            {
                string fullname = "";
                foreach (FileInfo fi in (new DirectoryInfo(smubiaolujin)).GetFiles("*.ini"))
                {
                    fullname = fi.FullName;
                    //过程信息
                    if (fullname.IndexOf(sgongweis) > -1)//
                    {
                        listView1.Items.Add(sgongweis);
                        cbbpzwj.Items.Add(sgongweis);
                    }
                }
            }
        }
        public void getsqlpeizhi(string sininame="")
        {
            listView2.Items.Clear();
            string ssql = string.Format("select * from gongweisetting where xh='{0}' and gongwei='{1}'", cbbjcx.Text, cbbgongwei.Text);
            if (sininame.Length > 0)
            {
                ssql = ssql + string.Format(" and ininame='{0}'", sininame);
            }
            DataTable dt = GetTable(ssql);
            foreach (DataRow dr in dt.Rows)
            {
                ListViewItem li = new ListViewItem();
                li.Text = dr["ininame"].ToString();
                li.SubItems.Add(dr["ip"].ToString());
                li.SubItems.Add(dr["date"].ToString());
                listView2.Items.Add(li);
            }
        }

        private void 预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string smubiaolujin = string.Format("{0}\\{1}", System.Windows.Forms.Application.StartupPath,lblini.Text);
            readiniForm1 obj = new readiniForm1();
            obj.Text = lblini.Text;
            obj.str = Read(smubiaolujin);
            if (obj.str.Length < 1)
            {
                MessageBox.Show("配置文件内容为空");
                return;
            }
            obj.ShowDialog();
            //getsqlpeizhi();

        }

        private void 预览ToolStripMenuItem1_Click(object sender, EventArgs e)
        {

            //string smubiaolujin = string.Format("{0}\\{1}", System.Windows.Forms.Application.StartupPath, lblini.Text);
            //string sneirong = Read(smubiaolujin);
            string ssql = string.Format("select * from gongweisetting where xh='{0}' and gongwei='{1}' and ininame='{2}'", cbbjcx.Text, cbbgongwei.Text, lblini.Text);
            DataTable dt = GetTable(ssql);

            if (dt.Rows.Count < 1)
            {
                MessageBox.Show("查不到该记录");
                return;
            }
            readiniForm1 obj = new readiniForm1();
            obj.Text = lblini.Text;
            obj.str = dt.Rows[0]["neirong"].ToString();
            obj.ShowDialog();
        }
        public string Read(string path)
        {
            //string filePath = @"E:\123\456.txt";
            string sreturn = "";
            try
            {
                if (File.Exists(path))
                {
                    sreturn = File.ReadAllText(path, System.Text.Encoding.GetEncoding("GB2312"));
                    //byte[] mybyte = Encoding.UTF8.GetBytes(sreturn);
                    //sreturn = Encoding.UTF8.GetString(mybyte);
                }
                else
                {
                    MessageBox.Show("文件不存在");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return sreturn;
        }
        //public string Read(string path)
        //{
        //    string sreturn = "";
        //    StreamReader sr = new StreamReader(path, Encoding.Default);
        //    String line;
        //    while ((line = sr.ReadLine()) != null)
        //    {
        //        sreturn+=line.ToString()+"\r\n";
        //    }
        //    return sreturn;
        //}
        public void Write(string path,string sneirong)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("GB2312"));
            //开始写入
            sw.Write(sneirong);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem li in listView1.SelectedItems)
            {
                lblini.Text = li.Text;
            }
        }
        private string GetIpAddress()
        {
            string hostName = Dns.GetHostName();   //获取本机名
            IPHostEntry localhost = Dns.GetHostByName(hostName);    //方法已过期，可以获取IPv4的地址
            //IPHostEntry localhost = Dns.GetHostEntry(hostName);   //获取IPv6地址
            IPAddress localaddr = localhost.AddressList[0];

            return localaddr.ToString();
        }
        private void 发送到数据库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lbljcx.Text == "" || lblgongwei.Text == "")
            {
                MessageBox.Show("检测线或工位名称不能为空！请先设置");
                return;
            }
            if (lbljcx.Text != cbbjcx.Text || lblgongwei.Text != cbbgongwei.Text)
            {
                if (MessageBox.Show("检测站线或工位名称与数据库配置不一致，是否上传？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
            }
            if (upload(lbljcx.Text, lblgongwei.Text,lblini.Text))
            {
                MessageBox.Show("上传成功");
                getsqlpeizhi();
            }
            else
            {
                MessageBox.Show("上传失败");
            }
        }

        private void 下载到本地ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (lbljcx.Text != cbbjcx.Text || lblgongwei.Text != cbbgongwei.Text)
            {
                if (MessageBox.Show("检测站线或工位名称不一致，是否上传？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
            }
            try
            {
                download(lblini.Text);
                MessageBox.Show("下载完成");
                getbendipeizhi();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public bool upload(string sjcxex,string sgongweiex, string sininame)
        {
            bool b = false;
            try
            {
                string smubiaolujin = string.Format("{0}\\{1}", System.Windows.Forms.Application.StartupPath, sininame);
                string sneirong = Read(smubiaolujin);
                string ssql = string.Format("select * from gongweisetting where xh='{0}' and gongwei='{1}' and ininame='{2}'", sjcxex, sgongweiex, sininame);
                DataTable dt = GetTable(ssql);
                if (dt.Rows.Count > 0)
                {
                    ssql = string.Format("update gongweisetting set neirong='{3}',date='{4}',ip='{5}' where xh='{0}' and gongwei='{1}' and ininame='{2}'",
                    sjcxex, sgongweiex, sininame,
                    sneirong, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), GetIpAddress());

                }
                else
                {
                    ssql = string.Format("insert into gongweisetting (xh,gongwei,ininame,neirong,date,ip) values ('{0}', '{1}' ,'{2}','{3}','{4}','{5}') ",
                    sjcxex, sgongweiex, sininame,
                    sneirong, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), GetIpAddress());
                }
                b = InsertDB(ssql);
            }
            catch(Exception )
            {}

            return b;
        }
        public void download(string sininame)
        {

            string ssql = string.Format("select * from gongweisetting where xh='{0}' and gongwei='{1}' and ininame='{2}'", cbbjcx.Text, cbbgongwei.Text, sininame);
            DataTable dt = GetTable(ssql);

            if (dt.Rows.Count < 1)
            {
                MessageBox.Show("查不到该记录");
                return;
            }

            if (!Directory.Exists(string.Format("{0}\\配置文件备份", System.Windows.Forms.Application.StartupPath)))
            {
                Directory.CreateDirectory(string.Format("{0}\\配置文件备份", System.Windows.Forms.Application.StartupPath));
            }

            string sneirong = dt.Rows[0]["neirong"].ToString();
            string smubiaolujinbeifen = string.Format("{0}\\配置文件备份\\{2}{1}", System.Windows.Forms.Application.StartupPath, sininame, DateTime.Now.ToString("yyyyMMddHHmmss"));
            string smubiaolujin = string.Format("{0}\\{1}", System.Windows.Forms.Application.StartupPath, sininame);
            try
            {
                File.Move(smubiaolujin, smubiaolujinbeifen);
            }
            catch { }
                Write(smubiaolujin, sneirong);
        }

        private void listView2_SelectedIndexChanged(object sender, EventArgs e)
        {

            foreach (ListViewItem li in listView2.SelectedItems)
            {
                lblini.Text = li.Text;
            }
        }

        private void cbbjcx_SelectedIndexChanged(object sender, EventArgs e)
        {

            getsqlpeizhi();
        }

        private void cbbgongwei_SelectedIndexChanged(object sender, EventArgs e)
        {

            getsqlpeizhi();
        }

        private void skinBut_speed_Click(object sender, EventArgs e)
        {
            if (lbljcx.Text == "" || lblgongwei.Text == "")
            {
                MessageBox.Show("检测线或工位名称不能为空！请先设置");
                return;
            }
            if (lbljcx.Text != cbbjcx.Text || lblgongwei.Text != cbbgongwei.Text)
            {
                if (MessageBox.Show("检测站线或工位名称与数据库配置不一致，是否上传？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
            }
            foreach (ListViewItem li in listView1.Items)
            {
                upload(lbljcx.Text, lblgongwei.Text, li.Text);
            }
            getsqlpeizhi();
            MessageBox.Show("上传完成！");
        }

        private void cbbpzwj_SelectedIndexChanged(object sender, EventArgs e)
        {

            getsqlpeizhi(cbbpzwj.Text);
        }

        public void baocunshezhiGW()
        {
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\系统信息.ini";
            string path1 = string.Format(@"{0}", path);
            iniclass objini = new iniclass();
            objini.Ini(path1);
            objini.Writue("系统信息", "检测线名称", cbbjcx.Text);
            objini.Writue("系统信息", "检测工位名称", cbbgongwei.Text);
        }
        private void skinButton1_Click(object sender, EventArgs e)
        {
            if (lbljcx.Text != cbbjcx.Text || lblgongwei.Text != cbbgongwei.Text)
            {
                if (MessageBox.Show("检测站线或工位名称不一致，是否上传？", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
                    return;
            }
            baocunshezhiGW();
            foreach (ListViewItem li in listView2.Items)
            {
                download(li.Text);
            }
            getbendipeizhi();
            MessageBox.Show("下载完成");
        }

        /// <summary>
        /// 数据库配置
        public static string sDataBaseIp;
        public static string sDataBaseName;
        public static string sDataBaseUserName;
        public static string sDataBasePwd;

        public void getSQLSZ()
        {
            iniclass objini = new iniclass();
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\数据库设置.ini";
            string path1 = string.Format(@"{0}", path);
            objini.Ini(path1);
            sDataBaseIp = objini.ReadValue("设置", "数据库IP");
            sDataBaseName = objini.ReadValue("设置", "数据库名称");
            sDataBaseUserName = objini.ReadValue("设置", "用户");
            sDataBasePwd = objini.ReadValue("设置", "密码");


        }
        public DataTable GetTable(string sSQL)
        {
            getSQLSZ();
            DataTable dttt = new DataTable();
            if (sDataBaseIp.Length < 1)
                return dttt;
            try
            {
                string connectionstring = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};", sDataBaseIp, sDataBaseName, sDataBaseUserName, sDataBasePwd);
                SqlConnection sqlconn = new SqlConnection(connectionstring);
                sqlconn.Open();
                SqlCommand cmd = new SqlCommand(sSQL, sqlconn);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                sqlconn.Close();
                return ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return dttt;
            }
        }

        ////数据库操作部分
        public bool InsertDB(string sql)
        {
            getSQLSZ();
            if (sDataBaseIp.Length < 1)
                return false;
            string connectstr = string.Format("Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID={2};Password={3};", sDataBaseIp, sDataBaseName, sDataBaseUserName, sDataBasePwd);
            SqlConnection sqlcnn = new SqlConnection(connectstr);
            //try
            {
                //打开数据库
                sqlcnn.Open();
                SqlCommand cmd = new SqlCommand(sql, sqlcnn);
                //执行插入操作，并返回受影响的行数
                int i = cmd.ExecuteNonQuery();
                //如果受影响的行数小于一则说明操作失败了
                if (i < 1)
                    return false;
                //关闭数据库
                sqlcnn.Close();
            }
            //catch (Exception er)
            //{
            //    string temp = er.Message.ToString();
            //    MessageBox.Show(temp);
            //    return false;
            //}
            return true;
        }
    }
}
